<template>
  	<el-upload class="avatar-uploader" :action="uploadaction" :data="postData" :on-success="handleAvatarSuccess" :show-file-list="false" :before-upload="beforeUpload" >
        <img v-if="imgUrl" :src="imgUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>

<script>
import CryptoJS from 'crypto-js'
export default {
   props: {
    fiedName: {
      type: String,
      default: '',
    },
    showImgUrl: {
      type: String,
      default: '',
    },
  },
data() {
    return {
        uploadaction: 'https://up-z2.qiniup.com/',
        postData: {
            token: ''
        },
        postToken: '',
        imgUrl: this.showImgUrl
    }
  },
  created: function() {
    this.postData.token = this.qiniuuptoken()
    console.log(this.postData.token)
    },
  methods:{
    // 上传文件到七牛云
    async upqiniu (req) {
        let filetype = ''
      if (req.file.type === 'image/png') {
        filetype = 'png'
      } else {
        filetype = 'jpg'
      }
      const keyname = 'lytton' + new Date() + Math.floor(Math.random() * 100) + '.' + filetype
      // 从后端获取上传凭证token
        const formdata = new FormData()
        formdata.append('file', req.file)
        formdata.append('token', this.postToken)
        formdata.append('key', keyname)
        // 获取到凭证之后再将文件上传到七牛云空间

        console.log(formdata)
        let res = await this.$store.dispatch("postImg", formdata);
        this.imageUrl = 'http://img.yuanqicao.com/' + res.data.key
    },
     // 验证文件合法性
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleAvatarSuccess(res, file) { //上传成功后在图片框显示图片
        var imageUrl = 'https://img.yuanqicao.com/' + res.key
        this.imgUrl = imageUrl
        this.$emit('setImg',{
          imageUrl,
          fiedName: this.fiedName
        })
    },
    qiniuuptoken() {
        var deadline = Math.round(new Date().getTime() / 1000 + 86400)
        // var jsonstring = `{"scope": 'yuanqicao',"deadline:" ${deadline}`
        var jsonstring = '{"scope":"' + 'yuanqicao' + '","deadline":' + deadline + '}'
        var encoded = this.base64encode(jsonstring)
        var hash = CryptoJS.HmacSHA1(encoded, "pL53nWzK3JzZd09gYXVdV3GTAG4Us6eE5e1IAesq")
        var encoded_signed = hash.toString(CryptoJS.enc.Base64)
        var token = '4Y0TZ57lYvCa7ntkjKvTGBUkbIzZpGE-qKuR_jge' + ':' + this.safe64(encoded_signed) + ':' + encoded
        return token
    },
    base64encode(str) {
        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
        var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1)
        var out, i, len;
        var c1, c2, c3;
        len = str.length;
        i = 0;
        out = "";
        while(i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if(i == len) {
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt((c1 & 0x3) << 4);
                out += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if(i == len) {
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                out += base64EncodeChars.charAt((c2 & 0xF) << 2);
                out += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            out += base64EncodeChars.charAt(c3 & 0x3F);
        }
        return out;
    },
    safe64(base64) {
        base64 = base64.replace(/\+/g, "-");
        base64 = base64.replace(/\//g, "_");
        return base64;
    },
  },
  watch:{
    showImgUrl(val) {
      this.imgUrl = val
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader{
  img{
    max-width: 100%;
  }
}
</style>
